package com.wise.service.portal.content.categorys;

import com.wise.entities.content.Product;
import com.wise.entities.content.ProductCategory;
import com.wise.framework.dao.SqlSelect;
import com.wise.framework.daomodel.DaoList;
import com.wise.summer.v1.portal.content.categorys.ListCategorys;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author shaoming
 * @date 2019-09-10
 */
@Service
@SummerService
public class ListCategorysService implements SummerServiceBean<ListCategorys> {

	@Override
	public void sum(ListCategorys summer) {
		if (summer.getCategoryType() == null) {
			summer.setCategoryType(0);
		}
		List<ProductCategory> allMenu = getAllProductCategory(summer.getCategoryType());
		List<ListCategorys.Result> menuList = getChild(allMenu, it -> StringUtils.isEmpty(it.getParentId()) && it.isShowStatus());

		summer.setSummerResult(menuList);
	}

	/**
	 * 查询所有
	 *
	 * @return
	 */
	private List<ProductCategory> getAllProductCategory(int categoryType) {
		SqlSelect selec = SqlSelect.selec("*")
				.fromClassName(ProductCategory.class)
				.eqLang(ProductCategory._lang)
				.eq(Product._categoryType, categoryType)
				;
		return DaoList.s(ProductCategory.class, selec);
	}

	/**
	 * 获取子集合
	 *
	 * @param allProductCategory 所有集合
	 * @param predicate
	 * @return
	 */
	private List<ListCategorys.Result> getChild(List<ProductCategory> allProductCategory, Predicate<ProductCategory> predicate) {
		List<ProductCategory> childList = allProductCategory.stream()
				.filter(predicate)
				.sorted(order().thenComparing(ProductCategory::getCreationDate))
				.collect(Collectors.toList());

		/* 递归 */
//		for (ProductCategory ProductCategory : childList) {
//			ProductCategory.setChildList(getChild(allProductCategory, it -> Objects.equals(ProductCategory.getId(), it.getParentId())));
//		}
		/* 退出递归条件 */
		return CollectionUtils.isEmpty(childList) ? null : childList.stream().map(it -> {
			return ListCategorys.Result.builder()
					.id(it.getId())
					.categoryName(it.getCategoryName())
					.alias(it.getAlias())
					.path(it.getPath())
					.fileName(it.getFileName())
					.build();
		}).collect(Collectors.toList());
	}

	/**
	 * 排序
	 */
	private Comparator<ProductCategory> order() {
		return (o1, o2) -> {
			if (!o1.getSort().equals(o2.getSort())) {
				return o1.getSort() - o2.getSort();
			}
			return 0;
		};
	}
}
